import Duck from 'extensible-duck'
import produce from 'immer'
import { Datasets as DatasetsNorm } from './norm'

export default new Duck({
  namespace: 'admin',
  store: 'dataset',
  types: ['SET_ACTIVE_TAB', 'RECIVE_DATASETS', 'SET_ACTIVE_DATASET'],
  initialState: { activeTab: 'overview', activeDataset: undefined },
  reducer: produce((draft, action, duck) => {
    switch (action.type) {
      case duck.types.SET_ACTIVE_TAB:
        draft.activeTab = action.value
        break
      case duck.types.RECIVE_DATASETS:
        draft.datasets = DatasetsNorm(action.value.servers)
        break
      case duck.types.SET_ACTIVE_DATASET:
        draft.activeDataset = action.name
        break
      default:
        break
    }
  }),
  selectors: {
    activeTab: state => state.dataset.activeTab,
    datasets: state => state.dataset.datasets,
    activeDatasetId: (state) => {
      const { activeDataset } = state.dataset
      const dataset = state.dataset.datasets.entities.dataset[activeDataset]
      if (dataset) {
        return dataset.id
      }
      return undefined
    },
    activeDataset: state => state.dataset.activeDataset,
  },
  creators: duck => ({
    actionSetActiveTab: value => ({ type: duck.types.SET_ACTIVE_TAB, value }),
    actionReciveDatasets: value => ({ type: duck.types.RECIVE_DATASETS, value }),
    actionSetActiveDataset: name => ({ type: duck.types.SET_ACTIVE_DATASET, name }),
  }),
})
